#include "mainwindow.h"
#include <QApplication>
#include <QTranslator>
#include <QtSingleApplication>
#include "cabinetclient.h"
#include "linklog.h"
#include "linksettings.h"
#include "ccrashstack.h"
#include <QTimer>

int main(int argc, char *argv[])
{
    backtrace_reg();

    QtSingleApplication a(argc, argv);
    if (a.isRunning()) {
        return EXIT_SUCCESS;
    }

    initLog(&a);

    MainWindow w;
    CabinetClient client(&w);

    a.setActivationWindow(&w);
    w.setWindowFlags(Qt::Tool);

    QObject::connect(&client, &CabinetClient::sig_clientLogin, &w, &MainWindow::slt_clientLogin);
    QObject::connect(&client, &CabinetClient::sig_statusChange, &w, &MainWindow::slt_statusChange);
    QObject::connect(&client, &CabinetClient::sig_task_start, &w, &MainWindow::slt_task_start);
    QObject::connect(&client, &CabinetClient::sig_task_done, &w, &MainWindow::slt_task_done);
    QObject::connect(&w, &MainWindow::download_default_dir_changed, &client, &CabinetClient::slt_ReloadConfig);

    QObject::connect(&client, &CabinetClient::sig_file_dialog_show, [&w](){
        if (w.isMinimized()) {
            w.showNormal();
        }

        //设置窗口置顶
#ifdef Q_OS_WIN32
        ::SetWindowPos(HWND(w.winId()), HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
        ::SetWindowPos(HWND(w.winId()), HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
        ::SetWindowPos(HWND(w.winId()), HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
#endif

        w.show();
        w.activateWindow();
    });
    QObject::connect(&client, &CabinetClient::sig_file_dialog_hide, &w, &MainWindow::hide);

    client.init();

    return a.exec();
}
